<?php

namespace App\Http\Controllers\API;

use App\Services\QiniuService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use zgldh\QiniuStorage\QiniuStorage;

class FileAPIController extends Controller
{
    /**
     * @api {get} api/qiniu/token  获取七牛token
     * @apiVersion 0.1.0
     * @apiName getQiniuToken
     * @apiGroup Common
     * @apiSuccessExample Success-Response:
     *  HTTP/1.1 200 OK
     */
    public function getQiniuToken(Request $request)
    {
        $uploadToken = QiniuService::getQiniuToken();
        return new JsonResponse(['uptoken' => $uploadToken]);
    }

    /**
     * @api {post} api/qiniu/upload  上传图片
     * @apiVersion 0.1.0
     * @apiName uploadFile
     * @apiGroup Common
     * @apiSuccessExample Success-Response:
     *  HTTP/1.1 200 OK
     * {
     * "code": 0,
     * "msg": "ok",
     * "data": "http://ovhnd16c5.bkt.clouddn.com/imagebc6a6c26318e52e4c19748236711bbbb.jpg"
     * }
     */
    public function uploadFile(Request $request)
    {
        // 判断是否有文件上传
        if ($request->hasFile('file')) {
            // 获取文件,file对应的是前端表单上传input的name
            $file = $request->file('file');

            // 初始化
            $disk = QiniuStorage::disk('qiniu');
            // 重命名文件
            $fileName = md5($file->getClientOriginalName() . time() . rand()) . '.' . $file->getClientOriginalExtension();

            // 上传到七牛
            $bool = $disk->put('image/' . $fileName, file_get_contents($file->getRealPath()));
            // 判断是否上传成功
            if ($bool) {
                $path = $disk->downloadUrl('image/' . $fileName);
                return $this->success($path);
            }
            return $this->fail(-1, '上传失败');
        }
        return $this->fail(-1, '没有该文件');
    }
}
